import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { Role } from "@/types/role";
import { roleApi } from "@/apis/role";

export const useRoleStore = defineStore("role", () => {
  // State
  const roles = ref<Role[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);
  const currentRole = ref<Role | null>(null);
  const total = ref(0);
  const currentPage = ref(1);
  const pageSize = ref(10);

  // Getters
  const roleCount = computed(() => roles.value.length);

  // Actions
  const fetchRoles = async (params?: { page?: number; pageSize?: number; name?: string }) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await roleApi.getPageRoles(params);
      roles.value = response.data.list;
      total.value = response.data.total;
      currentPage.value = response.data.page;
      pageSize.value = response.data.pageSize;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "获取角色列表失败";
      console.error("Failed to fetch roles:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const createRole = async (roleData: Omit<Role, "id" | "createdAt" | "updatedAt">) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await roleApi.createRole(roleData);
      roles.value.push(response.data);
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "创建角色失败";
      console.error("Failed to create role:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const updateRole = async (id: number, roleData: Partial<Role>) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await roleApi.updateRole(id, roleData);
      const index = roles.value.findIndex((role) => role.id === id);
      if (index !== -1) {
        roles.value[index] = response.data;
      }
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "更新角色失败";
      console.error("Failed to update role:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const deleteRole = async (id: number) => {
    loading.value = true;
    error.value = null;
    try {
      await roleApi.deleteRole(id.toString());
      roles.value = roles.value.filter((role) => role.id !== id);
    } catch (err) {
      error.value = err instanceof Error ? err.message : "删除角色失败";
      console.error("Failed to delete role:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const clearError = () => {
    error.value = null;
  };

  const setCurrentRole = (role: Role | null) => {
    currentRole.value = role;
  };

  return {
    // State
    roles,
    loading,
    error,
    currentRole,
    total,
    currentPage,
    pageSize,
    // Getters
    roleCount,
    // Actions
    fetchRoles,
    createRole,
    updateRole,
    deleteRole,
    clearError,
    setCurrentRole,
  };
});
